+server.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import auth from "$lib/server/auth.js";
  2. import Recipe from "$lib/server/models/Recipe.js";
  3. import {error, json} from "@sveltejs/kit";
  4. export async function POST({request, cookies, params}){
  5. const user = await auth(cookies, false);
  6. const body = await request.json();
  7. if(!body.name) error(400, "Recipe name required");
  8. if(body.ingredients.length <= 0) error(400, "Ingredients required");
  9. if(body.steps.length <= 0) error(400, "Preparation steps required");
  10. for(let i = 0; i < body.ingredients.length; i++){
  11. if(!body.ingredients[i].name) error(400, "Ingredient name required");
  12. const qty = body.ingredients[i].quantity;
  13. if(qty === undefined || qty === null || qty === ""){
  14. delete body.ingredients[i].quantity;
  15. }else if(qty <= 0){
  16. error(400, "Quantity must be greater than 0");
  17. }
  18. if(!body.ingredients[i].unit) body.ingredients[i].unit = "";
  19. }
  20. const recipe = await Recipe.findOne({_id: params.recipeId});
  21. recipe.name = body.name;
  22. recipe.ingredients = body.ingredients;
  23. recipe.steps = body.steps;
  24. recipe.notes = body.notes;
  25. recipe.private = body.private;
  26. recipe.updatedAt = new Date();
  27. await recipe.save();
  28. return json({msg: "success"}, {status: 200});
  29. }
  30. export async function DELETE({cookies, params}){
  31. const user = await auth(cookies, false);
  32. let recipe;
  33. try{
  34. recipe = await Recipe.findOne({_id: params.recipeId});
  35. if(!recipe || user._id.toString() !== recipe.user.toString()) error(403, "Forbidden");
  36. await Recipe.deleteOne({_id: params.recipeId});
  37. }catch(e){
  38. if(e.status === 403) error(403, "Forbidden");
  39. error(500, "Internal Server Error");
  40. }
  41. return json({msg: "success"}, {status: 200});
  42. }